package com.zuorenke;

import com.zuorenke.model.ClientUploadModel;
import com.zuorenke.serialize.support.json.JsonUtils;
import com.zuorenke.vertx.VertxUtil;
import io.vertx.core.*;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.asyncsql.AsyncSQLClient;
import io.vertx.ext.asyncsql.MySQLClient;
import io.vertx.ext.sql.ResultSet;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientOptions;

import java.util.ArrayList;
import java.util.List;

public class QpsVerticle extends AbstractVerticle {
	
	private AsyncSQLClient mysqlSQLClient;
	
	private int counter;
	
	public void start() {
		mysqlSQLClient = MySQLClient.createShared(vertx, config());
		Router router = Router.router(vertx);
		router.post("/").handler(this::query2);
		router.get("/").handler(this::query2);
		vertx.createHttpServer().requestHandler(req -> router.handle(req))
				.listen(8989);
	}
	
	private void query2(RoutingContext ctx) {
		query2(ctx.request());
		
	}
	private void query2(HttpServerRequest req) {
		String name = req.getParam("name");
		mysqlSQLClient.getConnection(ar -> {
//                System.out.println("ger Connection successed,name:"+name);
			String param = name;
			if(param == null){
//				param = "6205";
			}
			JsonArray params = new JsonArray();
			ar.result().queryWithParams(" select * " +
					" from ls_lesson a where courseSingleId = 6205 and a.isDeleted=0", params, asyncResult -> {
				ResultSet result = asyncResult.result();
				if (asyncResult.succeeded() && result.getNumRows() > 0) {
					req.response().putHeader("content-type", "application/json;charset=utf-8")
							.putHeader("counter",String.valueOf(counter++))
							.end(result.getRows().toString());
				} else {
					req.response().putHeader("content-type", "application/json;charset=utf-8")
							.end(new JsonObject().put("result", "error").toBuffer());
				}
				ar.result().close();
			});
		});
	}
	
	// 4000吞吐量
	public static void main(String[] args) {
		List<ClientUploadModel> uploadModelList = new ArrayList<>();
		ClientUploadModel uploadModel = new ClientUploadModel();
		uploadModel.setClientTime(1111111L);
		uploadModel.setLessonId(6205L);
		uploadModel.setErrorCode("1232s");
		uploadModelList.add(uploadModel);
		
		uploadModel = new ClientUploadModel();
		uploadModel.setClientTime(22222L);
		uploadModel.setLessonId(6205L);
		uploadModel.setErrorCode("1232s");
		uploadModelList.add(uploadModel);
		
		System.out.println(JsonUtils.toJson(uploadModelList));

//		DeploymentOptions asyncClientVerticleOptions = new DeploymentOptions()
//				.setConfig(new JsonObject().put("host", "192.168.20.68")
//						.put("username","exschool_test")
//						.put("password","exschool2012")
////                        .put("database", "welucky")
//						.put("database", "lesson")
//						.put("maxPoolSize",100)).setInstances(1);
//		Vertx.vertx().deployVerticle(QpsVerticle.class.getName(),asyncClientVerticleOptions);
//		webClient.get(443, "lesson.leke.cn", "/monitor.html").ssl(true).send(ar ->{
//			System.out.println(ar.result().body());
//		});
		
//		WebClientOptions webClientOptions = new WebClientOptions()
//				.setSsl(true).setConnectTimeout(10000).setFollowRedirects(true).setMaxRedirects(5);
		WebClient webClient = WebClient.create(Vertx.vertx());
		MultiMap map = MultiMap.caseInsensitiveMultiMap();
//		map.set("ticket", "VG1jOVBRPT07TkQ0M056UStQak0zTmpjPTs2Ng==");
		map.set("data", "{\"ids\":[\"3b47656eddcd2a8df7ce65be60a35206pptx37119c\"]}");
//		webClient.postAbs("https://api.leke.cn/api/n/invoke.htm?ticket=VG1jOVBRPT07TkQ0M056UStQak0zTmpjPTs2Ng==&_m=getFiles&_s=fs")
		webClient.post(443,"api.leke.cn","/api/n/invoke.htm")
				.timeout(10000).ssl(true)
				.addQueryParam("ticket", "VG1jOVBRPT07TkQ0M056UStQak0zTmpjPTs2Ng==")
				.addQueryParam("_m", "getFiles")
				.addQueryParam("_s", "fs")
		.sendForm(map, ar -> {
			if(ar.failed()){
				System.out.println("fail : "+ar.result().bodyAsString());
			}else{
				System.out.println(ar.result().bodyAsString());
			}
		});
	}
	
	
	
}
